package com.eostoken.eos_wallet.ui.fragment;

import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.MapUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseFragment;
import com.eostoken.eos_wallet.bean.MsgCodeBean;
import com.eostoken.eos_wallet.bean.WithdrawIndexBean;
import com.eostoken.eos_wallet.db.MgpWallet;
import com.eostoken.eos_wallet.helper.DialogConfirmListener;
import com.eostoken.eos_wallet.helper.DialogHelper;
import com.eostoken.eos_wallet.mvp.mode.AppsModel;
import com.eostoken.eos_wallet.mvp.presenter.AppsPresenterImpl;
import com.eostoken.eos_wallet.mvp.view.AppsView;
import com.eostoken.eos_wallet.utils.Constants;
import com.eostoken.eos_wallet.utils.RSAUtils;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.qmuiteam.qmui.layout.QMUILinearLayout;
import com.qmuiteam.qmui.layout.QMUIRelativeLayout;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import java.math.BigDecimal;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.eostoken.eos_wallet.utils.Constants.ADD_ORDER;
import static com.eostoken.eos_wallet.utils.Constants.MGP_SYMBOL;
import static com.eostoken.eos_wallet.utils.Constants.WITHD_RAW_INDEX;

public class ExtractionYieldFragment extends BaseFragment<AppsModel, AppsView, AppsPresenterImpl> implements AppsView {
    @BindView(R.id.topBar)
    QMUITopBar topBar;
    @BindView(R.id.walletIconTv)
    QMUIRadiusImageView walletIconTv;
    @BindView(R.id.walletNameTv)
    AppCompatTextView walletNameTv;
    @BindView(R.id.walletAccountTv)
    AppCompatTextView walletAccountTv;
    @BindView(R.id.walletInfoLayout)
    QMUIRelativeLayout walletInfoLayout;
    @BindView(R.id.quantityTitleTv)
    AppCompatTextView quantityTitleTv;
    @BindView(R.id.balanceTv)
    AppCompatTextView balanceTv;
    @BindView(R.id.quantityEt)
    AppCompatEditText quantityEt;
    @BindView(R.id.orderValueTv)
    AppCompatTextView orderValueTv;
    @BindView(R.id.layout1)
    RelativeLayout layout1;
    @BindView(R.id.line)
    View line;
    @BindView(R.id.text1)
    AppCompatTextView text1;
    @BindView(R.id.layout2)
    RelativeLayout layout2;
    @BindView(R.id.layout)
    QMUILinearLayout layout;
    @BindView(R.id.nextstepBtn)
    QMUIRoundButton nextstepBtn;

    private MgpWallet wallet;
    private String accountName;
    private int mRadius;
    private String moneyType;
    private WithdrawIndexBean withdrawIndexBean;
    private QMUIDialog qmuiDialog;
    String money = "0.0000";

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_mortgage_mining;
    }

    @Override
    protected void initData() {
        wallet = WalletUtils.getCurrentWallet(getActivity());
        accountName = wallet.getCurrentAccountName();
        mRadius = QMUIDisplayHelper.dp2px(getContext(), 8);
        Bundle bundle = getArguments();
        moneyType = bundle.getString("moneyType", "2");
        getWithdrawIndex();
    }

    @Override
    protected void initView(View contentView) {
        topBar.setTitle(getString(R.string.str_my_motivation));
        topBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popOrFinish();
            }
        });

        walletInfoLayout.setRadius(mRadius);
        walletNameTv.setText(wallet.getWalletName());
        walletAccountTv.setText(accountName);
        quantityTitleTv.setText(getString(R.string.str_total_recoverable_amount));
        balanceTv.setVisibility(View.GONE);
        layout2.setVisibility(View.GONE);
        text1.setText(getString(R.string.str_service_charge));
        setEditableEditText(quantityEt, false);
    }

    private void updataView() {

        String lockMoney = "0";
        String serviceCharge = "0.00";
        String nextUnlockTime = "";
        if (withdrawIndexBean != null) {
            if (withdrawIndexBean.getCode() == 0) {
                WithdrawIndexBean.DataBean dataBean = withdrawIndexBean.getData();
                if (dataBean != null) {
                    money = dataBean.getMoney();
                    lockMoney = dataBean.getLockMoney();
                    serviceCharge = dataBean.getServiceCharge();
                    nextUnlockTime = dataBean.getNextUnlockTime();
                }
            } else {
                ToastUtils.showShort(withdrawIndexBean.getMsg());
            }
        }

        quantityEt.setText(ObjectUtils.isEmpty(money) ? "0.0000" : money);
        orderValueTv.setText((ObjectUtils.isEmpty(serviceCharge) ? "0.00" : serviceCharge) + (ObjectUtils.equals("1", moneyType) ? MGP_SYMBOL : "ETH"));
    }

    @OnClick(R.id.nextstepBtn)
    public void onViewClicked() {
        BigDecimal bigDecimal;
        if (ObjectUtils.isEmpty(money)) {
            bigDecimal = BigDecimal.ZERO;
        } else {
            bigDecimal = new BigDecimal(money);
        }
        if (bigDecimal.compareTo(BigDecimal.ZERO) > 0) {
            if (qmuiDialog == null) {
                qmuiDialog = DialogHelper.showEditTextDialog(getActivity(), getString(R.string.str_password_authentification),
                        getString(R.string.str_enter_password), getString(android.R.string.ok), getString(android.R.string.cancel), listener, true);
            }
            qmuiDialog.show();
        } else {
            ToastUtils.showShort(R.string.str_no_withdrawal_limit);
        }
    }

    DialogConfirmListener listener = new DialogConfirmListener() {
        @Override
        public void onClick(QMUIDialog dialog, View view, int index) {
            dialog.dismiss();
            EditText editText = (EditText) view;
            String contrastPassword = editText.getText().toString().trim();
            if (ObjectUtils.equals(contrastPassword, wallet.getWalletPassword())) {
                getWithdrawAddOrder();
            } else {
                ToastUtils.showShort(StringUtils.getString(R.string.str_wrong_password));
            }
            editText.setText("");
        }
    };


    @Override
    public void updateView(Object data, int responseSuccessCode) {
        switch (responseSuccessCode) {
            case WITHD_RAW_INDEX:
                if (data != null) {
                    withdrawIndexBean = GsonUtils.fromJson(data.toString(), WithdrawIndexBean.class);
                    updataView();
                }
                break;
            case ADD_ORDER:
                int string;
                if (data != null) {
                    MsgCodeBean msgCodeBean = GsonUtils.fromJson(data.toString(), MsgCodeBean.class);
                    if (msgCodeBean.getCode() == 0) {
                        string = R.string.str_withdrawal_success;
                    } else {
                        string = R.string.str_withdrawal_fail;
                    }
                } else {
                    string = R.string.str_withdrawal_fail;
                }
                ToastUtils.showShort(string);
                break;
        }
    }

    @Override
    public void onFailure(Object data, int responseFailCode) {
        switch (responseFailCode) {
            case WITHD_RAW_INDEX:

                break;
            case ADD_ORDER:
                ToastUtils.showShort(R.string.str_withdrawal_fail);
                break;
        }
    }

    @Override
    public void updateView(boolean success, Object o1, Object o2) {

    }

    @Override
    public AppsModel createModel() {
        return new AppsModel();
    }

    @Override
    public AppsView createView() {
        return this;
    }

    @Override
    public AppsPresenterImpl createPresenter() {
        return new AppsPresenterImpl(getActivity());
    }

    @Override
    public void finishRefresh() {

    }

    public void setEditableEditText(AppCompatEditText editText, boolean isEnabled) {
        editText.setEnabled(isEnabled);//去掉点击时编辑框下面横线:
        editText.setFocusable(isEnabled);//不可编辑
        editText.setFocusableInTouchMode(isEnabled);//不可编辑
    }

    public void getWithdrawIndex() {
        try {
            Map params = MapUtils.newHashMap();
            params.put("address", accountName);
            params.put("moneyType", moneyType);
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            presenter.requestPortData(content, WITHD_RAW_INDEX);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getWithdrawAddOrder() {
        try {
            Map params = MapUtils.newHashMap();
            params.put("address", accountName);
            params.put("moneyType", moneyType);
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            presenter.requestPortData(content, ADD_ORDER);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //取消全屏设置
        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        BarUtils.setStatusBarColor(getActivity(), ContextCompat.getColor(getActivity(), R.color.app_color_blue));
    }
}
